package com.hn.vue.config;

import com.hn.vue.security.CustomUserDetailsService;
import com.hn.vue.security.MyAccessDeniedHandler;
import com.hn.vue.security.MyAuthenticationFailureHandler;
import com.hn.vue.security.MyAuthenticationSuccessHandler;
import com.hn.vue.verify.ImageCodeVerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;


import java.util.Arrays;


/**
 * hanni
 * 2019/3/6 0006
 * 11:35
 */
@Configuration //将配置信息注入到spring容器中
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启pre验证功能
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")  //明确指定使用的是哪个实体bean
    private UserDetailsService userDetailsService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PersistentTokenRepository tokenRepository;

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Autowired
    private ImageCodeVerifyFilter imageCodeVerifyFilter;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

//        http.httpBasic(); 弹框出现
        http.addFilterBefore(imageCodeVerifyFilter,UsernamePasswordAuthenticationFilter.class)
                .formLogin().loginPage("/login")//设置登录页，在这个请求里面返回页面路径
                .successHandler(myAuthenticationSuccessHandler)//成功处理器
                .failureHandler(myAuthenticationFailureHandler)//失败处理器
                .and()
                .rememberMe()
                .tokenRepository(tokenRepository)
                .tokenValiditySeconds(30)
                .and()
                .authorizeRequests() //对请求的页面进行认证
                .antMatchers("/login.html","/login","/verifycode/image").permitAll() //需要放过的页面
                .anyRequest().authenticated()  //其他的全部都需要认证
                .and()
                .logout().permitAll(); //放过退出请求h
        http.csrf().disable();//关闭跨域请求

        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);



    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
       /* auth.userDetailsService(userDetailsService).passwordEncoder(
                new PasswordEncoder() {
                    @Override
                    public String encode(CharSequence charSequence) {
                        return charSequence.toString();
                    }

                    @Override
                    public boolean matches(CharSequence charSequence, String s) {
                        return s.equals(charSequence.toString());
                    }
                }
        );*/
    }
    /**
     * 获取系统中的用户数据
     * @return
     */
    @Bean("InMoryUserDetailsService")
    public UserDetailsService InMoryUserDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        String password = new BCryptPasswordEncoder().encode("123");
        System.out.println(password);
        userDetailsManager.createUser(new User("admin",password,Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))));
        userDetailsManager.createUser(new User("刘备",password,Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))));
        return userDetailsManager;
    }


    @Bean("customUserDetailsService")
    public UserDetailsService customUserDetailsService() {

        return new CustomUserDetailsService();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){

        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();

        jdbcTokenRepository.setJdbcTemplate(jdbcTemplate);


        return jdbcTokenRepository;

    }
}
